{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## array - very much like list but of same primitive data types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "As byte string: b'some random string'\n",
      "As array: array('b', [115, 111, 109, 101, 32, 114, 97, 110, 100, 111, 109, 32, 115, 116, 114, 105, 110, 103])\n"
     ]
    }
   ],
   "source": [
    "#initialization of an array\n",
    "import array\n",
    "import binascii\n",
    "\n",
    "my_str = b'some random string'\n",
    "arr = array.array('b', my_str)\n",
    "\n",
    "print('As byte string:', my_str)\n",
    "print('As array:', arr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initial: array('i', [0, 1, 2, 3, 4])\n",
      "Extended: array('i', [0, 1, 2, 3, 4, 0, 1])\n",
      "Slicing: array('i', [1, 2, 3, 4])\n",
      "Enumeration:\n",
      "[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 0), (6, 1)]\n"
     ]
    }
   ],
   "source": [
    "#manipulating arrays\n",
    "\n",
    "ar = array.array('i', range(5))\n",
    "print('Initial:', ar)\n",
    "\n",
    "ar.extend(range(2))\n",
    "print('Extended:', ar)\n",
    "\n",
    "print('Slicing:', ar[1:5])\n",
    "\n",
    "print('Enumeration:')\n",
    "print(list(enumerate(ar)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initial: array('i', [0, 1, 2, 3, 4, 0, 1])\n",
      "In Byte form: b'00000000010000000200000003000000040000000000000001000000'\n",
      "A: array('i', [0, 1, 2, 3, 4, 0, 1])\n"
     ]
    }
   ],
   "source": [
    "#Convert array into bytes and vice-versa - using tobytes() and frombytes()\n",
    "\n",
    "print('Initial:', ar)\n",
    "\n",
    "as_bytes = ar.tobytes()\n",
    "print('In Byte form:', binascii.hexlify(as_bytes))\n",
    "\n",
    "\n",
    "a = array.array('i')\n",
    "a.frombytes(as_bytes)\n",
    "print('A:', a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
